package com.cyh.pangu.offer;

import com.cyh.pangu.offer.common.ListNode;
import com.cyh.pangu.offer.common.ListUtils;

public class Offer22 {

    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode former = head;
        ListNode second = head;
        for (int i = 0; i < k; i++) {
            if (former  == null) {
                return null;
            }
            former = former.next;
        }

        while (former != null) {
            former = former.next;
            second = second.next;
        }
        return second;
    }

    public ListNode getKthFromEnd_chajin(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        ListNode begin = head;
        int i = 0;
        ListNode end = head;
        int j = 0;
        while (end.next != null) {
            j++;
            if (j - i >= k) {
                begin = begin.next;
                end = end.next;
                if (end == null) {
                    return begin;
                }
                i++;
            } else{
                end = end.next;
                if (end == null) {
                    return begin;
                }
            }
        }
        return begin;
    }

    public static void main(String[] args) {
        Offer22 offer22 = new Offer22();
        ListNode node = new ListNode();
        int[] nums = {1,2,3,4,5,6,7};
        ListNode head = ListUtils.buildList(nums);
        ListUtils.printList(head);
        ListNode result = offer22.getKthFromEnd(head, 3);
        System.out.println("=======================");
        ListUtils.printList(result);
    }
}
